<?php
/**
 * 邮件分组控制器类
 * Created by PhpStorm.
 * User: Liujianlin
 * Date: 2017/6/5
 * Time: 16:29
 */

namespace app\controllers\crontab;


use yii;
use app\models\marketing\MailGroup;
use app\models\marketing\MailSubgroup;
use app\models\marketing\MailSendlist;
use app\components\TemplateMarket;
use yii\data\Pagination;
use app\components\smarty\SmartyNewRenderer;
use app\components\EmailMarket;
use app\models\marketing\MailGroupEmailTypeStatistics;
use app\components\Site;
class 
AddMailGroupController extends \app\base\Controller
{
   
    /**
     * 为了兼容以前的接口数据，旧的一些数据先在这里做成配置
     */
    protected $autoSendConfig = [
        'gamiss' => [
            
            'cart' => [ // 购物车邮件
                'add_group_time' => 57600, // 开始生成分组的时间点（距离当天0点0分的秒数）
                // 'add_group_time' => 0, // 开始生成分组的时间点（距离当天0点0分的秒数）
                'is_old' => 1, // 旧版本
                'template_type_compaign'=>'eocart',
                'filter' => [ // 过滤条件相关
                    'filter_type' => 1, // 过滤某几天发过邮件的用户，并且是某几天添加到购物车的邮件
                    'filter_condition' => [
                        'filter_nearest_day' => 10, // 最近10天发过邮件的要过滤掉
                        
                    ],  
                ], 
                'isNeedCoupon'=>1, // 是否需要生成coupon码
                'select' => [ // 查询条件
                    'add_cart_day' => 3, // 最近三天加入购物车的商品
                ],
                'otherVal' => [ // 自定义变量
                ],
                'goods_type' => 1,
                'user_email_type' => 1,
                'auto_create_id' => 0,
                
            ],
        ],
//         'twinkledeals' => [
//            
//            'cart' => [ // 购物车邮件
//                // 'add_group_time' => 57600, // 开始生成分组的时间点（距离当天0点0分的秒数）
//                'add_group_time' => 0, // 开始生成分组的时间点（距离当天0点0分的秒数）
//                'is_old' => 1, // 旧版本
//                'template_type_compaign'=>'eocart',
//                'filter' => [ // 过滤条件相关
//                    'filter_type' => 1, // 过滤某几天发过邮件的用户，并且是某几天添加到购物车的邮件
//                    'filter_condition' => [
//                        'filter_nearest_day' => 10, // 最近10天发过邮件的要过滤掉
//                        
//                    ],  
//                ], 
//                'isNeedCoupon'=>0, // 是否需要生成coupon码
//                'select' => [ // 查询条件
//                    'add_cart_day' => 4, // 最近四天加入购物车的商品
//                ],
//                'otherVal' => [ // 自定义变量
//                ],
//                'goods_type' => 1,
//                'user_email_type' => 1,
//                'auto_create_id' => 0,
//                
//            ],
//        ],
        'zaful' => [
            'cart' => [ // 购物车邮件
                'add_group_time' => 55800, // 开始生成分组的时间点（距离当天0点0分的秒数）
                // 'add_group_time' => 0, // 开始生成分组的时间点（距离当天0点0分的秒数）
                'is_old' => 0, // 新版本
                'template_type_compaign'=>'eocart',
                'filter' => [ // 过滤条件相关排重过滤
                    'filter_type' => 2, // 过滤掉某几天发过浏览记录邮件的相关用户
                    'filter_type_compaign'=>'eoscan', // 过滤掉某一种邮件类型
                    'filter_condition' => [
                        'filter_nearest_day' => 7,  
                    ],
                   
                ],
                'isNeedCoupon' => 0,
                'select' => [ // 查询条件
                   //'add_cart_day' => 3, // 最近三天加入购物车的商品
                ],
                
                
                'otherVal' => [ // 自定义变量
                    'goods_url1',
                    'goods_img1',
                    'goods_name1',
                    'shop_price1',
                    'market_price1',
                    
                    'goods_url2',
                    'goods_img2',
                    'goods_name2',
                    'shop_price2',
                    'market_price2',
                    
                    'goods_url3',
                    'goods_img3',
                    'goods_name3',
                    'shop_price3',
                    'market_price3',
                    
                    'goods_url4',
                    'goods_img4',
                    'goods_name4',
                    'shop_price4',
                    'market_price4',
                    
                    'goods_url5',
                    'goods_img5',
                    'goods_name5',
                    'shop_price5',
                    'market_price5',
                ],
                'goods_type' => 1,
                'user_email_type' => 1,
                'auto_create_id' => 0,
            ]
        ]
         
    ];
    
    protected $couponCodeApi = [
        'gamiss' => [
            'dev'=>'http://gamiss.com.trunk.s1.egomsl.com/syn/syn_edm_coupon.php',
            'test'=>'http://gamiss.com.trunk.s1.egomsl.com/syn/syn_edm_coupon.php',
            'product'=>'http://www.gamiss.com/syn/syn_edm_coupon.php',
        ]
    ];
    
    /**
     * 初始化
     */
    public function init()
    {
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。
    }
    
    /**
     * 获取合适条件的用户数据
     */
    private function getData($webName,$condition)
    {   
        $commonWhere = "";
        $commonWhere .= ' u.is_complaint=0';   //没有被投诉
        $commonWhere .= ' and u.is_received_promo = 1 and u.is_received_custom_promo > 0 and u.is_block=0 and u.is_bound=0';   //没退订,黑名单,硬弹
        $curWhere = "";
        $curBjTime = \yii::$app->bjTime->time();
        
        // 过滤掉一些数据start
        if (isset($condition['filter']) && isset($condition['filter']['filter_type'])) {
            $siteId = Yii::$app->params['sites']['marketing_email']['web_config'][$webName]['site_id'];
            
            // 把相应过滤条件的数据状态状态设置为2
            $filterTypeCompaign = !empty($condition['filter']['filter_type_compaign']) ? $condition['filter']['filter_type_compaign'] : "";
            
            $lastUpdateTime = $curBjTime - $condition['filter']['filter_condition']['filter_nearest_day'] * 24 * 3600;
            
            $goodsType = !empty($condition['goods_type']) ? $condition['goods_type'] : 0;
            $autoCreateId = !empty($condition['auto_create_id']) ? $condition['auto_create_id'] : 0;
            $userEmailType = !empty($condition['user_email_type']) ? $condition['user_email_type'] : 0;
            // 过滤其他的一些类型的邮件数据
            $updateCommonWhere = " 1 = 1  ";
            if ($filterTypeCompaign) {
                $filterWhere = " and group_name like '%{$filterTypeCompaign}%'";
            } else {
                $filterWhere = "";
            }
            if ($filterWhere) {
                $updateSql = " update user_{$webName}_goods_data as cg, 
                      (select site_user_id from mail_sendlist_{$webName} as ms, 
                          (select group_id from mail_group where {$updateCommonWhere} {$filterWhere} and (add_date >= {$lastUpdateTime} or group_last_send >= {$lastUpdateTime}) and site_id = {$siteId}) as mg
                      where ms.group_id = mg.group_id) as m
                set cg.send_state = 2 where  cg.site_user_id = m.site_user_id and cg.send_state = 0";
            } else {
                $updateSql = " update user_{$webName}_goods_data as cg LEFT JOIN user_{$webName} as u on cg.site_user_id = u.site_user_id set cg.send_state = 2 where cg.send_state = 0 and u.last_sent_time >= {$lastUpdateTime}";
            }
           
          
//            echo $updateSql;
//            echo '<br>';
            // 执行相关的语句
            yii::$app->db->createCommand($updateSql)->execute();
 
        }
        // 过滤掉一些数据end
        // 组装额外查询条件start
      
        $curWhere .= " and cg.send_state = 0 and cg.auto_create_id={$autoCreateId} ";
        if (!empty($condition['is_old'])) { // 旧版相关数据
            // 组装where
            $curWhere .= " and cg.goods_type={$goodsType}";
        } else {
            $curWhere .= " and cg.user_email_type={$userEmailType}";
        }
        
        // 如果有最近几天时间的限制则也要加上
        if (!empty($condition['select']['add_cart_day'])) {
             $daysAgo =  date("Y-m-d",strtotime((1-$condition['select']['add_cart_day']).' day'));
            $stime = strtotime($daysAgo." 00:00:00");
            $etime = strtotime($daysAgo." 23:59:59");
            $curWhere .= " and cg.add_cart_time > {$stime} and cg.add_cart_time <  {$etime} ";
        }
        // 组装额外查询条件end
        // 组装sql相关
        $selectUserSql = "select u.user_id,cg.id from user_{$webName}_goods_data as cg LEFT JOIN user_{$webName} as u on cg.site_user_id = u.site_user_id where {$commonWhere} {$curWhere}";
//        echo $selectUserSql;
//        echo '<br>';
        if (isset($selectUserSql)) {
            $userIdArr = yii::$app->db->createCommand($selectUserSql)->queryAll();
            return $userIdArr;
        } else {
            return false;
        }
        
    }
    public function rand_keys($length)
    {
        $key = '';
        $pattern='1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        for($i=0;$i<$length;$i++)
        {
           $key .= $pattern{mt_rand(0,35)};    //生成php随机数
        }
        return $key;
    }

    /**
     * 更改表中数据状态
     */
    private function updateData($webName,$condition,$haveAddIdArr,$siteId,$trackCode) {
        $originalCondition = $condition;
        $curWhere = " 1=1 ";
        if (isset($condition['cart'])) {
            
            $condition = $condition['cart'];
        } else { // 其他邮件类型先不处理
            return false;
        }
        $haveAddIdStr = join(',',$haveAddIdArr);
        
        // 如果有最近几天时间的限制则也要加上
        if (!empty($condition['select']['add_day'])) {
            $daysAgo =  date("Y-m-d",strtotime((1-$condition['select']['add_cart_day']).' day'));
            $stime = strtotime($daysAgo." 00:00:00");
            $etime = strtotime($daysAgo." 23:59:59");
            $curWhere .= " and cg.add_cart_time > {$stime} and cg.add_cart_time <  {$etime} ";
        }
        
        
        if (isset($condition['filter']) && isset($condition['filter']['filter_type'])) {
            
            
            $curBjTime = \yii::$app->bjTime->time();
            $lastSendTime = $curBjTime - $condition['filter']['filter_condition']['filter_nearest_day'] * 24 * 3600;
            if (!empty($condition['is_old'])) {
                include (ROOT_PATH."/template/{$webName}_template.php");
            } 
            
            foreach ($haveAddIdArr as $haveAddIdVal) {
                
                // 先获取当前记录的goods_list和其它的相关数据
                $getGoodsInfoSql = "select * from user_{$webName}_goods_data where id = {$haveAddIdVal}";
                $goodsInfoCur = yii::$app->db->createCommand($getGoodsInfoSql)->queryOne();
             
                if (!empty($condition['isNeedCoupon'])) {
                    $couponCode = $this->rand_keys(4); // 生成coupon码
                }
                $otherVal = [];
                // 组装相关变量
                if (!empty($condition['is_old'])) {
                    $template_replace_html = $this->mergeCartCouponHtml($siteId,$goodsInfoCur,$trackCode,$couponCode,$webName,$template_content);
                    $otherVal['cart_goods_info'] = $template_replace_html;
                } else {
                    if (!empty($condition['otherVal'])) {
                        $goodsInfoOther = unserialize($goodsInfoCur['goods_list']);
                        
                        if (!empty($goodsInfoOther)) {
                            $curKey = 1;
                            foreach ($goodsInfoOther as $goodsInfoK => $goodsInfoV) {
                                $goodsInfoV['goods_url'] = str_replace("https://" , "", $goodsInfoV['goods_url']);
                                $otherVal['goods_url' . $curKey] = str_replace("http://","",$goodsInfoV['goods_url']);
                                
                                $goodsInfoV['goods_img'] = str_replace("https://" , "", $goodsInfoV['goods_img']);
                                $otherVal['goods_img' . $curKey] = str_replace("http://","",$goodsInfoV['goods_img']);
                                $otherVal['goods_name' . $curKey] = $goodsInfoV['goods_name'];
                                $otherVal['shop_price' . $curKey] = $goodsInfoV['shop_price'];
                                $otherVal['market_price' . $curKey] = $goodsInfoV['market_price'];
                                $curKey++;
                            }
                        }
                    }
                }
                $otherValJson = json_encode($otherVal);
                // 更新数据添加couponCode和额外变量
                if ($goodsInfoCur) {
                    $cartGoodsInfo = json_decode($goodsInfoCur['goods_list'],true);
                    
                    $paramsBind = [':otherValJson' =>  $otherValJson];
                    if ($cartGoodsInfo['goods_state'] == 1 && !empty($condition['isNeedCoupon'])) {
                        $updateSql = "update user_{$webName}_goods_data set coupon_code='{$couponCode}',other_vars = :otherValJson where id = {$haveAddIdVal}";
                    } else {
                        $updateSql = "update user_{$webName}_goods_data set other_vars = :otherValJson where id = {$haveAddIdVal}";
                    }
                    yii::$app->db->createCommand($updateSql)->bindValues($paramsBind)->execute();
                }
            }
            
            if ($haveAddIdStr) {
                // 组装相关变量
                $updateUserSql = "update user_{$webName}_goods_data set send_state=1  where id in ($haveAddIdStr) and send_state=0";
                yii::$app->db->createCommand($updateUserSql)->execute();
            }
            $updateUserSql = "update user_{$webName}_goods_data set send_state=2 where send_state=0 and goods_type=1 and auto_create_id=0 and {$curWhere}";
            yii::$app->db->createCommand($updateUserSql)->execute();
        }
        
    }
    
    private function mergeCartCouponHtml($siteId,$goodsInfoCur,$trackCode,$couponCode,$webName,$template_content) {
       
        $tableName = "user_{$webName}_goods_data";
        $cartGoodsHtml = '';
        
        
       
        //exit;
        $cartGoodsInfo =  json_decode($goodsInfoCur['goods_list'],true);
       
        if ($cartGoodsInfo) {
            $cartGoodsHtml = $template_content['cart_goods_info'];  
            // 组装相关数据
            $cartGoodsHtml =  str_replace('{url_title}' , $cartGoodsInfo['url_title'].'?'.$trackCode , $cartGoodsHtml);
            $cartGoodsHtml = str_replace('{eo_price}' , "$".$cartGoodsInfo['goods_price'] , $cartGoodsHtml);
            $cartGoodsHtml = str_replace('{goods_img}' , $cartGoodsInfo['goods_img'] , $cartGoodsHtml);
            if ( $cartGoodsInfo['goods_state'] == 1 ) {
                $cartGoodsHtml .= $template_content['coupon_code_info'];
                $cartGoodsHtml = str_replace('{coupon_code}' , $couponCode , $cartGoodsHtml);
            }
        } 
        
        return $cartGoodsHtml;
    }
    /**
     * 添加发送分组
     */
    public function actionAddGroup()
    {
        ignore_user_abort(true); 
        set_time_limit(0);
        $siteObj = new Site();
        foreach ($this->autoSendConfig as $webName=>$webMailInfo) {
            $curBjTime = \yii::$app->bjTime->time();
            $curDate = \yii::$app->bjTime->date('Y-m-d');
            $curDayStart = \yii::$app->bjTime->strtotime($curDate." 00:00:00");
            $data = [];
            $data['module_name'] = "marketing_email";
            // 各种邮件的处理
            // 查看是否到已经添加队列的时间
            if ($curBjTime - $curDayStart >= $webMailInfo['cart']['add_group_time']) {  // 说明已经到了生成分组时间
                
                // 获取合适条件的用户数据
                $userIdArr = $this->getData($webName,$webMailInfo['cart']);
               
                echo '<pre>';
              
                var_dump($userIdArr);
                
               
                $haveAddIdArr = [];
                if ($userIdArr) {
                    foreach ($userIdArr as $userIdTemp) {
                        $data['user_id'][] = $userIdTemp['user_id'];
                        $haveAddIdArr[] =  $userIdTemp['id'];
                    }
                }
               
                
                if (isset($data['user_id']) && $data['user_id']) {
                    $data['site_id'] =  Yii::$app->params['sites']['marketing_email']['web_config'][$webName]['site_id'];
                    if (isset($webMailInfo['cart']['template_type_compaign'])) {
                        // 查询相关的邮件模版
                        $getTemplateIdSql = "select mt.template_id,mt.id,mt.track_code from mail_template as mt left join template_type as tt on tt.id = mt.type_id where tt.template_type_compaign = '{$webMailInfo['cart']['template_type_compaign']}' and mt.is_use=1 and mt.is_del=0 and mt.status=1 and mt.site_id={$data['site_id']}";
                        $tempInfo = yii::$app->db->createCommand($getTemplateIdSql)->queryOne();
                        $data['template_id'] = $tempInfo['template_id'];
                        $data['template_pk'] = $tempInfo['id'];
                        
                        if($tempInfo['track_code'])
                        {
                            $data['group_name'] = str_replace("{sendTime}", $curBjTime, $tempInfo['track_code']);
                            $data['group_name'] = str_replace("{sendDate}", \yii::$app->bjTime->date('ymd',$curBjTime), $data['group_name']);
                        }
                        
                        $data['utm_campaign'] = $data['group_name'];
                        $data['send_mode'] = 2;
                        $data['send_type'] = 0;
                        $data['send_type_time'] = 0;
                        $data['channel_id'] = 2;
                        $data['sender'] = Yii::$app->params['sites']['marketing_email']['web_config'][$webName]['api_email'];
                        $data['state'] = 1;
                        $data['start_time'] = $curBjTime;
                        $data['boot_time'] = $curBjTime;
                        $data['is_use_independent_ip'] = 0;
                        $data['is_fix_time_send'] = 0;
                        $data['track_code'] = "utm_source=mail_api&utm_medium=mail&utm_campaign=" . $data['utm_campaign'];
                        $data['is_auto_group'] = 1; // 自动添加的分组
                        $groupModel = new MailGroup();
                        $sendListModel = new MailSendlist();
                        $statModel = new MailGroupEmailTypeStatistics();
                        $trans = Yii::$app->db->beginTransaction();
                        try {
                           
                            $groupId = $groupModel->addGroup($data);
                           
                            $count = $sendListModel->addSendListByUserId($data['site_id'], $groupId, $data['channel_id'],
                                $data['template_pk'], $data['user_id'],1,$haveAddIdArr);
                            if (0 == $count) {
                                $groupModel->updateGroupByCondition(['group_id' => $groupId], ['is_del' => 1]);
                            } else {
                                $groupModel->updateGroupByCondition(['group_id' => $groupId], ['total_count' => $count]);
                                $statModel->addMailStatItem($groupId, $data['site_id']);
                            }
                            
                            // 更改表中goods_data数据状态
                            $this->updateData($webName,$webMailInfo,$haveAddIdArr,$data['site_id'],$data['track_code']);
                            $trans->commit();
                        } catch (\Exception $e) {
                           $trans->rollBack();
                          exit("添加分组失败：系统繁忙，请稍后重试");
                        }
                    } else {
                        continue;
                    }
                  
                } else {
                    continue;
                } 
               
                
            }
        
        }
      
    }
    
    /*
     * 检测网站是否在计划发送时间后一个小时之后生成分组，并将结果发送监控系统
     * liugang 20170831
     */
    public function actionCheckIsAddMailGroup()
    {
            set_time_limit(0);
            $oldEmailType = array(
                1 => '购物车',
                2 => '热销',
                3 => '收藏夹'
            );
            $emailType = array(
                1 => '购物车',
                2 => '大码'
            );
            $this->autoSendConfig = array_merge($this->autoSendConfig,array(
                'selfcheck' => [//自检配置信息
            
                    'cart' => [ // 购物车邮件
                        'add_group_time' => 0, // 开始生成分组的时间点（距离当天0点0分的秒数）
                        // 'add_group_time' => 0, // 开始生成分组的时间点（距离当天0点0分的秒数）
                        'is_old' => 1, // 旧版本
                        'template_type_compaign'=>'eocart',
                        'filter' => [ // 过滤条件相关
                            'filter_type' => 1, // 过滤某几天发过邮件的用户，并且是某几天添加到购物车的邮件
                            'filter_condition' => [
                                'filter_nearest_day' => 10, // 最近10天发过邮件的要过滤掉

                            ],  
                        ], 
                        'isNeedCoupon'=>1, // 是否需要生成coupon码
                        'select' => [ // 查询条件
                            'add_cart_day' => 3, // 最近三天加入购物车的商品
                        ],
                        'otherVal' => [ // 自定义变量
                        ],
                        'goods_type' => 1,
                        'user_email_type' => 1,
                        'auto_create_id' => 0,
                         'brief_code'       => 'SCK',
                    ],
                ],
            ));
             
            foreach ($this->autoSendConfig as $webName=>$webMailInfo) {
                $curBjTime = \yii::$app->bjTime->time();
                $curDate = \yii::$app->bjTime->date('Y-m-d');
                $curDayStart = \yii::$app->bjTime->strtotime($curDate." 00:00:00");
                $data = [];
                $data['module_name'] = "marketing_email";
                // 各种邮件的处理
                // 查看是否到已经添加队列的时间
                $hours = $webName == 'selfcheck' ? 0 : 3600;
                if ($curBjTime - $curDayStart >= $webMailInfo['cart']['add_group_time'] + $hours) {  // 生成分组之后1个小时

                        //查看分组表中有没有生成分组
                        $whereArr = array(
                            'group_name' => ($webName == 'selfcheck' ? $webMailInfo['cart']['brief_code'] : Yii::$app->params['sites']['marketing_email']['web_config'][$webName]['brief_code']) . '_' . $webMailInfo['cart']['template_type_compaign'],
                            'start_time' => $curDayStart + $webMailInfo['cart']['add_group_time'],
                            'is_auto_group' => 1
                        );
                        $groupModel = new MailGroup();
                        if(!$groupModel->isExsitGroupByCondition($whereArr))
                        {
                            //不存在分组，判断是否有推送发送邮件数据
                             // 获取合适条件的用户数据
                            if (!empty($webMailInfo['cart']['is_old'])) { // 旧版相关数据

                                $email_type = array_key_exists($webMailInfo['cart']['goods_type'],$oldEmailType) ? $oldEmailType[$webMailInfo['cart']['goods_type']] : '';
                            } else {
                                $email_type = array_key_exists($webMailInfo['cart']['user_email_type'],$emailType) ? $emailType[$webMailInfo['cart']['user_email_type']] : '';
                            }
                            if($webName == 'selfcheck')
                            {
                                $error = 'EMP营销邮件，自检网站推送数据为0，'.$email_type.'邮件未在 '.\yii::$app->bjTime->date('Y-m-d H:i:s',$curDayStart + $webMailInfo['cart']['add_group_time']).' 生成发送分组';
                                \app\helpers\Monitor::reportCheckAddGroupError($error,1,1);
                            }
                            else
                            {
                                $userIdArr = $this->getData($webName,$webMailInfo['cart']);


                                $haveAddIdArr = [];
                                if ($userIdArr) {
                                    foreach ($userIdArr as $userIdTemp) {
                                        $data['user_id'][] = $userIdTemp['user_id'];
                                        $haveAddIdArr[] =  $userIdTemp['id'];
                                    }
                                }
                                
                                if (isset($data['user_id']) && $data['user_id']) {//有推送发送邮件数据

                                    $error = 'EMP营销邮件，'.$webName.'网站推送数据不为0，'.$email_type.'邮件未在 '.\yii::$app->bjTime->date('Y-m-d H:i:s',$curDayStart + $webMailInfo['cart']['add_group_time']).' 生成发送分组';
                                   
                                    \app\helpers\Monitor::reportCheckAddGroupError($error,2);

                                }else{//没有推送的要发送的邮件数据
                                    $error = 'EMP营销邮件，'.$webName.'网站推送数据为0，'.$email_type.'邮件未在 '.\yii::$app->bjTime->date('Y-m-d H:i:s',$curDayStart + $webMailInfo['cart']['add_group_time']).' 生成发送分组';
                                    
                                    \app\helpers\Monitor::reportCheckAddGroupError($error,1);
                                }
                            }
                            
                        }
                        
                }

            }
            
    }
    
    
    
   
}
